/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
package com.wealth.bbs.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wealth.bbs.entity.Reply;
import com.wealth.bbs.entity.Topic;
import com.wealth.bbs.entity.TopicAppraise;
import com.wealth.bbs.entity.TopicPic;
import com.wealth.bbs.enums.TopicAppraiseEnum;
import com.wealth.bbs.repository.TopicAppraiseDao;
import com.wealth.bbs.repository.TopicDao;
import com.wealth.bbs.repository.TopicPicDao;
import com.wealth.bbs.service.ITopicPicService;
import com.wealth.bbs.service.ITopicService;
import com.wealth.bbs.vo.ReplyVO;
import com.wealth.bbs.vo.TopicAppraiseVO;
import com.wealth.bbs.vo.TopicPicVO;
import com.wealth.bbs.vo.TopicVO;
import com.wealth.member.entity.Member;
import com.wealth.member.repository.MemberDao;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.ResultObject;

/**
 * @author zhu
 * @version 1.0
 * @since 1.0
 */

@Component 
public class TopicServiceImpl extends BaseServiceImpl<Topic> implements ITopicService {

	@Autowired
	private MemberDao memberDao;
	
	@Autowired
	private TopicDao topicDao;
	@Autowired
	private TopicPicDao topicPicDao;
	@Autowired
	private TopicAppraiseDao topicAppraiseDao;
	@Autowired
	private ITopicPicService topicPicService;	
	@Override
	public List<TopicVO> ajaxTopicVO(Long boardid, Long memberid,Integer isRecommend, Integer index, Integer offset)
			throws Exception {
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(0, offset, sort);
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:板块
		filters.add(new SearchFilter("board.id", Operator.EQ, boardid));
		//过滤:状态
		filters.add(new SearchFilter("status", Operator.EQ, StatusEnum.NORMAL.getValue()));
		//过滤:是否精华               
		filters.add(new SearchFilter("isRecommend", Operator.EQ, isRecommend));
		//过滤：id<index
		if(index!=-1){
			filters.add(new SearchFilter("id", Operator.LT, index));
		}
		Specification<Topic> spec = DynamicSpecifications.bySearchFilter(filters, Topic.class);
		Page<Topic> page  = topicDao.findAll(spec, pageRequest);
		
		/** ---- 组装vo ---*/
		List<TopicVO> volist = packaging(memberid, page);
		return volist;
	}
	
	@Override
	public ResultObject saveTopic(Topic topic, String picurls[],Long memberId) {
		
		try {
			//保存主题
			Member member = memberDao.findOne(memberId);
			topic.setStatus(StatusEnum.NORMAL.getValue());
			topic.setCreateTime(new Date());
			topic.setCreator(member.getNickname());
			topic.setMember(member);
			topicDao.save(topic);
			
			if (picurls != null && picurls.length > 0) {
				String pics[] = picurls;
				for (Object pic : pics) {
					TopicPic temp = new TopicPic(); 
					temp.setPicurl(pic.toString());
					temp.setTopic(topic);
					topicPicDao.save(temp);
				}
			}

			return   new  ResultObject("000", "发布主题成功", "");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	@Override
	public ResultObject appraiseTopic(Long topicid, Long memberid, Integer appraiseType, Integer status)
			throws Exception {
		
		TopicAppraise appraise = topicAppraiseDao.findByTopicIdAndMemberIdAndType(topicid, memberid, appraiseType);
		//修改
		if(appraise!=null){
			appraise.setStatus(status);
		//新增	
		}else{
			Member member = memberDao.findOne(memberid);
			appraise = new TopicAppraise();
			appraise.setCreator(member.getNickname());
			appraise.setCreateTime(new Date());
			appraise.setTopic(new Topic(topicid));
			appraise.setMember(member);
			appraise.setType(appraiseType);
			appraise.setStatus(status);
		}
		topicAppraiseDao.save(appraise);
		
		
		String msg = (appraiseType == TopicAppraiseEnum.SUPPORT.getValue())?"点赞":"踩";
		msg+=(status ==StatusEnum.NORMAL.getValue())?"成功":"取消";
		
		return new ResultObject("000", msg, "");
	}
	
	
	@Override
	public TopicVO getTopicVO(Long topicid, Long memberid) throws Exception {
		Topic po = topicDao.findOne(topicid);
		TopicVO vo = packagingForDetail(memberid, po);
		return vo;
	}
	
	
	
	/** 
	 * VOList 打包处理
	 * create by chan on 2016-09-13
	 */
	public List<TopicVO> packaging(Long memberid, Page<Topic> page) {
		List<Topic> polist = page.getContent();
		List<TopicVO> volist = new ArrayList<TopicVO>();
		for (Topic po : polist) {
			
			TopicVO vo = new TopicVO();						//vo初始化
			
			//帖子相关
			vo.setId(po.getId());
			vo.setName(po.getName());
			vo.setContent(po.getContent());
			vo.setCreateTime(po.getCreateTime());
			vo.setNickname(po.getMember().getNickname());
			vo.setHeadimgurl(po.getMember().getHeadimgurl());
			vo.setSex(po.getMember().getSex());
			vo.setStatus(po.getStatus());
			vo.setMemberid(po.getMember().getId());				//发帖人
			vo.setBoardid(po.getBoard().getId());
			vo.setCorpid(po.getBoard().getCorp().getId());
			vo.setPv(po.getPv());
			
			//回复数，赞数,踩数
			TopicAppraiseVO appraiseVO = new TopicAppraiseVO();
			List<TopicAppraise> topicAppraiseList = po.getTopicAppraiseList();
			for (TopicAppraise ta : topicAppraiseList) {
				if(ta.getMember().getId().equals(memberid) && ta.getType()==TopicAppraiseEnum.SUPPORT.getValue() && ta.getStatus() == StatusEnum.NORMAL.getValue() ){
					appraiseVO.setIsSupport(1);				//已赞
				}
				if(ta.getMember().getId().equals(memberid) && ta.getType()==TopicAppraiseEnum.AGAINST.getValue() && ta.getStatus() == StatusEnum.NORMAL.getValue() ){
					appraiseVO.setIsAgainst(1);				//已踩
				}
			}
			appraiseVO.setReplyNum(po.getReplyNum());		//回复数
			appraiseVO.setSupportNum(po.getSupportNum());	//点赞数	
			appraiseVO.setAgainstNum(po.getAgainstNum());	//踩数	
			vo.setTopicAppraiseVO(appraiseVO);				//vo设置
			
			//图片列表
			List<TopicPicVO> topicpicvolist = new ArrayList<TopicPicVO>();
			List<TopicPic> piclist = po.getTopicPicList();
			for (TopicPic pic : piclist) {
				TopicPicVO picvo = new TopicPicVO(); 
				picvo.setId(pic.getId());
				picvo.setPicurl(pic.getPicurl());
				topicpicvolist.add(picvo);
			}
			vo.setTopicPicList(topicpicvolist);				//vo设置
			volist.add(vo);											//volist设置
		}
		return volist;
	}
	
	
	
	/** 
	 * VO 打包处理
	 * create by chan on 2016-09-13
	 */
	public TopicVO packagingForDetail(Long memberid, Topic po) {
			
			TopicVO vo = new TopicVO();						//vo初始化
			
			//帖子相关
			vo.setId(po.getId());
			vo.setName(po.getName());
			vo.setContent(po.getContent());
			vo.setCreateTime(po.getCreateTime());
			vo.setNickname(po.getMember().getNickname());
			vo.setHeadimgurl(po.getMember().getHeadimgurl());
			vo.setSex(po.getMember().getSex());
			vo.setStatus(po.getStatus());
			vo.setMemberid(po.getMember().getId());				//发帖人
			vo.setBoardid(po.getBoard().getId());
			vo.setCorpid(po.getBoard().getCorp().getId());
			
			//回复数，赞数,踩数
			TopicAppraiseVO appraiseVO = new TopicAppraiseVO();
			List<TopicAppraise> topicAppraiseList = po.getTopicAppraiseList();
			for (TopicAppraise ta : topicAppraiseList) {
				if(ta.getMember().getId().equals(memberid) && ta.getType()==TopicAppraiseEnum.SUPPORT.getValue() && ta.getStatus() == StatusEnum.NORMAL.getValue() ){
					appraiseVO.setIsSupport(1);				//已赞
				}
				if(ta.getMember().getId().equals(memberid) && ta.getType()==TopicAppraiseEnum.AGAINST.getValue() && ta.getStatus() == StatusEnum.NORMAL.getValue() ){
					appraiseVO.setIsAgainst(1);				//已踩
				}
			}
			appraiseVO.setReplyNum(po.getReplyNum());		//回复数
			appraiseVO.setSupportNum(po.getSupportNum());	//点赞数	
			appraiseVO.setAgainstNum(po.getAgainstNum());	//踩数	
			vo.setTopicAppraiseVO(appraiseVO);				//vo设置
			
			
			//回复列表
			List<ReplyVO> replyvolist = new ArrayList<ReplyVO>();
			Collections.sort(po.getReplyList());
			int j=0;
			for (Reply reply : po.getReplyList()) {
				if(reply.getStatus()==StatusEnum.NORMAL.getValue()){
					//加载出10条
					if(j<10){
						ReplyVO rvo = new ReplyVO();
						rvo.setContent(reply.getContent());
						rvo.setId(reply.getId());
						rvo.setCreateTime(reply.getCreateTime());
						rvo.setNickname(reply.getMember().getNickname());
						rvo.setHeadimgurl(reply.getMember().getHeadimgurl());
						rvo.setSex(reply.getMember().getSex());
						if(reply.getMember().getId() == memberid || memberid == po.getMember().getId()){
							rvo.setIsDelete("1");
						}
						replyvolist.add(rvo);
					}
					j++;
				}
			}
			vo.setReplyList(replyvolist);					//vo设置
			
			//图片列表
			List<TopicPicVO> topicpicvolist = new ArrayList<TopicPicVO>();
			List<TopicPic> piclist = po.getTopicPicList();
			for (TopicPic pic : piclist) {
				TopicPicVO picvo = new TopicPicVO(); 
				picvo.setId(pic.getId());
				picvo.setPicurl(pic.getPicurl());
				topicpicvolist.add(picvo);
			}
			vo.setTopicPicList(topicpicvolist);				//vo设置
			
			return vo;
	}
		public void saveTopic(Topic topic) throws Exception{
			topic.setStatus(StatusEnum.NORMAL.getValue());
			topic.setCreateTime(new Date());
			topic.setIsRecommend(YesOrNoEnum.NO.getValue());
			topic.setPv(0);
			topicDao.save(topic);
			//商品图片
			List<TopicPic> picList = topic.getTopicPicList();
			for (TopicPic pic : picList) {
				pic.setTopic(topic);
				topicPicDao.save(pic);
			}
		}
		
		public void updateTopic(Topic topic) throws Exception{
			topicDao.save(topic);
			
			//删除关联的图片
			deletePics(topic.getId());
			
			//页面传入图片,新增
			List<TopicPic> picList = topic.getTopicPicList();
			for (TopicPic pic : picList) {
				if (pic.getId() == null && pic.getPicurl()!=null) {
					pic.setTopic(topic);
					topicPicDao.save(pic);
				}
			}
		}
		
		//删除数据库存储的图片
		private void deletePics(Long topicid) throws Exception{
			List<TopicPic> picList = topicPicService.findByPropertyName("topic.id", topicid, TopicPic.class);
			for (TopicPic pic : picList) {
				topicPicService.delete(pic);
			}
		}
}
